<!-- 邀请组件 -->
<template>
  <a-modal
    :visible="modalVisible"
    :title="modalTitle"
    :footer="null"
    @cancel="handleCancel(0)"
  >
    <a-form-model
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      :model="formData"
      ref="formRef"
      :rules="formRules"
    >
      <a-form-model-item :label="$t('all.autotext709')" prop="phone" style="display: flex;">
        <a-input v-model="formData.phone" @change="e => handleInputChange(e.target.value)" :placeholder="$t('all.autotext396')" />
        <div style="display: flex" v-if="$auth('PROJECT.PROJECT_MEMBER_ADD')">
          <div :style="{ marginRight: '10px' }">{{ $t('all.autotext5') }}?</div>
          <div><a @click="addFast">{{ $t('all.autotext373') }}</a></div>
        </div>
      </a-form-model-item>
      <a-form-item :label="$t('all.autotext551')">
        <a-input v-model="formData.account" disabled width="100%"/>
      </a-form-item>
      <a-form-item :label="$t('all.autotext977')">
        <a-input v-model="formData.name" disabled width="100%"/>
      </a-form-item>
      <a-form-model-item :label="$t('all.autotext374')" prop="roleId">
        <a-select v-model="formData.roleId" @change="roleChange">
          <a-select-option v-for="item in rolesList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item v-if="selectCode !== 'PM'" :label="$t('all.autotext1054')" prop="center">
        <a-select
          v-model="researchIds"
          mode="multiple"
          :disabled="disbaled"
          :maxTagCount="2"
          allowClear
        >
          <a-select-option v-for="item in centerList" :key="item.id" :value="item.id">
            {{ item.researchCenterNo }}-{{ item.orgName }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <!-- <a-form-model-item label="成员编号" prop="proUserNo">
        <a-input v-model="formData.proUserNo" placeholder="请输入成员编号" />
      </a-form-model-item> -->
      <a-row :gutter="48">
        <a-col :md="24" :sm="24">
          <a-button
            type="primary"
            :loading="submitting"
            @click="handleInvitation"
            style="float: right"
            :disabled="isSend"
          >
            {{ $t('all.autotext1162') }}
          </a-button>
        </a-col>
      </a-row>
    </a-form-model>
    <AddDrawer :addFastVisible="addFastVisible" @closeDrawer="closeDrawer" />
  </a-modal>
</template>

<script>



import { getAdminMessage, sendInvitationTeam } from '@/api/common'
import { getNewRolesList, centerList, researchIds } from '@/api/overview/member'
import AddDrawer from './components/AddDrawer'



export default {
  props: {
    projectId: { // 项目Id
      type: [String, Number],
      default: null
    },
    invitedType: { // 被邀请人类型
      type: Number,
      default: null
    },
    modalVisible: {
      type: Boolean,
      default: false
    },
    modalTitle: {
      type: String,
      default: ''
    }
  },
  components: {
    AddDrawer
  },
  data () {
    return {
      proId: '',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      },
      rolesList: [],
      isSend: true,
      addFastVisible: false,
      formData: {},
      invitationData: {},
      formRules: {
        phone: [
          { required: true, message: this.$t('all.autotext396'), trigger: 'change' },
          { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: this.$t('all.autotext140') }
        ],
        roleId: [{ required: true, message: this.$t('all.autotext367'), trigger: 'change' }],
        proUserNo: [
          { required: true, message: this.$t('all.autotext702'), trigger: 'change' },
          { pattern: /^[0-9a-zA-Z-_]{1,}$/, message: this.$t('all.autotext1400') }
        ]
      },
      submitting: false,
      disbaled: false,
      selectCode: '',
      researchIds: [],
      centerList: []
    }
  },
  watch: {
    modalVisible (e) {
      if (e) {
        this.getCenterList()
      }
    }
  },
  created () {
    const pd = localStorage.getItem('CURRENT_PROID')
    if (pd) {
      this.proId = parseInt(pd)
    }
    this.getNewRolesList()
  },
  methods: {
    // 点击快捷创建弹窗
    addFast () {
      this.addFastVisible = true
    },
    // 新建弹窗关闭
    closeDrawer () {
      this.addFastVisible = false
    },
    // 获取角色列表
    getNewRolesList () {
      if (this.proId) {
        getNewRolesList({ proId: this.proId }) // 注：传1是写死的
          .then(res => {
            const isEnabled = status => +status === 1
            this.rolesList = res.filter(item => item.code !== 'PROJECT_ADMIN' && item.code !== 'SYS_BIZ' && item.code !== 'Subjects' && isEnabled(item.status))
          })
          .catch(() => {})
      }
    },
    // 获取中心列表
    getCenterList () {
      const params = {
        proId: this.proId,
        deleted: 0, // 后端让传的写死的字段
        pageSize: 1000,
        pageNumber: 1
      }
      centerList(params).then(res => {
        this.centerList = [
          ...res.content
        ]
      })
    },
    // 手机号码输入框改变
    handleInputChange (value) {
      if (value.length === 11) {
        // 请求接口
        getAdminMessage({ phone: value })
          .then(res => {
            if (res && res.id) { // 判断是否返回了数据 （判断是否有id即可）
              this.formData.userId = res.id
              this.formData.name = res.name
              this.formData.account = res.account
              this.isSend = false
              this.isPi()
            } else {
              this.$message.error(this.$t('all.autotext5'))
            }
          })
        this.roleChange()
      } else {
        this.formData.userId = null
        this.formData.name = null
        this.formData.account = null
        this.isSend = true
      }
    },
    // 点击发送邀请
    handleInvitation () {
      // if (!this.formData || !this.formData.account) {
      //   this.$message.warning('未找到与此手机号相关的信息，请校验号码是否正确')
      //   return false
      // }
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.invitationData.proId = this.projectId || this.proId // 父组件传过来的项目id
          this.invitationData.type = this.invitedType // 父组件传来的被邀请人类型
          this.invitationData.phone = this.formData.phone // 输入的电话号码
          this.invitationData.invitedUserId = this.formData.userId // 根据电话号码获取的被邀请人id
          this.invitationData.roleId = this.formData.roleId // 角色id
          this.invitationData.proUserNo = this.formData.proUserNo // 角色id
          this.invitationData.pm = 0 // 角色id
          this.invitationData.name = this.formData.name
          this.invitationData.account = this.formData.account
          this.invitationData.researchIds = this.researchIds.join(',')
          this.rolesList.forEach(item => {
            if (item.id === this.formData.roleId) this.invitationData.roleCode = item.code
          })
          this.submitting = true
          this.inviteMember()
          sendInvitationTeam({ ...this.invitationData })
            .then(res => {
              this.submitting = false
              // 成功发送邀请后，通知父组件刷新列表
              this.handleCancel(1)
              this.$message.success(this.$t('all.autotext1386'))
            })
            .catch(() => {
              this.submitting = false
            })
        }
      })
    },
    // 点击取消对话框消失
    handleCancel (val) {
      this.$emit('closeInvitateModal', val)
      this.researchIds = []
      this.resetForm()
      this.disbaled = false
    },
    // 重置数据
    resetForm () {
      this.$refs.formRef.resetFields()
      this.isSend = true
      this.formData = {}
      this.selectCode = ''
    },
    async roleChange () {
      if (!this.formData.roleId || !this.formData.phone) return
      const code = this.rolesList.filter(item => item.id === this.formData.roleId)[0].code
      this.selectCode = code
    },
    async isPi () {
      const res = await researchIds({
        proId: this.proId,
        phone: this.formData.phone
      })
      if (res && res.researchId) {
        this.researchIds = String(res.researchId).split(',').map(Number)
        this.formData.roleId = res.roleId
        this.disbaled = true
      } else {
        this.researchIds = []
        this.$set(this.formData, 'roleId', '')
        this.disbaled = false
      }
    },
    // 添加团队成员埋点
    inviteMember () {}
  }
}
</script>
<style scoped lang="scss">

</style>
